<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    /**
     * 获取分类列表
     */
    public static function getCates(){
        $cates = self::orderBy("sort","desc")->orderBy("id","desc")->get();
        $cates = self::makeCates($cates);
        return $cates;
    }

    /**
     * 组织分类数据
     */
    private static function makeCates($data,$pid = 0,$level = 0){
        $arr = [];
        foreach($data as $item){
            if($item->pid == $pid){
                $item->level = $level;
                $arr[] = $item;
                $arrTemp = self::makeCates($data,$item->id,$level + 1);
                $arr = array_merge($arr,$arrTemp);
            }
        }
        return $arr;
    }

    /**
     * 获取所有的子分类
     */
    public static function getChildIdArr($id){
        $idArr[] = $id;
        $data  = self::all();
        $child = self::makeCates($data,$id);
        foreach($child as $item){
            $idArr[] = $item->id;
        }

        return $idArr;
    }
}
